package com.vq3.digitalizationsoftwareintegrates.Utils.DateUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vq3.digitalizationsoftwareintegrates.Entity.Enum.MessageType;
import com.vq3.digitalizationsoftwareintegrates.Entity.Info.ResultInfo;
import com.vq3.digitalizationsoftwareintegrates.Entity.Spot_Check.*;
import com.vq3.digitalizationsoftwareintegrates.Entity.Spot_Check.MongoDBEntity.MongoDB_S_C_WebSocketMessageEntity;
import com.vq3.digitalizationsoftwareintegrates.Entity.Spot_Check.MongoDBEntity.MongoDB_S_C_WebSocketSendMessageEntity;
import com.vq3.digitalizationsoftwareintegrates.Entity.User.ImportantNewsMessageEntity;
import com.vq3.digitalizationsoftwareintegrates.Entity.User.URole_TBEntity;
import com.vq3.digitalizationsoftwareintegrates.Mapper.Spot_Check.S_C_DatesMapper;
import com.vq3.digitalizationsoftwareintegrates.Mapper.Spot_Check.S_C_PointMapper;
import com.vq3.digitalizationsoftwareintegrates.Mapper.Spot_Check.S_C_Point_ContentMapper;
import com.vq3.digitalizationsoftwareintegrates.Service.MessageCenter.Impl.MessageCenterServiceImpl;
import com.vq3.digitalizationsoftwareintegrates.Servlet.WebSocket.WebSocketServer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.EncodeException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**定时任务调度中心
 * */

@Component("TaskUtils") // 把此类托管给 Spring，不能省略
public class TaskUtils {
    @Resource
    S_C_DatesMapper s_c_datesMapper;
    @Resource
    S_C_PointMapper s_c_pointMapper;
    @Resource
    S_C_Point_ContentMapper s_c_point_contentMapper;
    @Resource
    MessageCenterServiceImpl messageCenterService;

    /**每间隔0.1秒执行一次,快速补充测试数据用
     * */
        /*@Scheduled(fixedDelay = 10000)*/
    // 添加定时任务
        @Scheduled(cron = "0 0 1 * * ?") // cron表达式：每天凌晨1点触发
        public void S_C_addTomorrowDateTable() throws EncodeException, IOException {
            try {
                ResultInfo resultInfo = start();
                sendResult(resultInfo,false);
            }catch (EncodeException| IOException exception) {
                exception.printStackTrace();
            }
        }
    /**每间隔0.1秒执行一次,快速补充测试数据用
     * */
    /*@Scheduled(fixedDelay = 100)*/
        /**每天中午12点二次确认
         * */
        @Scheduled(cron = "0 0 12 * * ?")
        public void S_C_A_T_D_T_Secondary_Confirmation () throws EncodeException, IOException {
            try {
                ResultInfo resultInfo = start();
                resultInfo.setErrorMsg("点检业务严重异常！请联系系统管理员！");
                sendResult(resultInfo,true);
            }catch (EncodeException| IOException exception) {
                exception.printStackTrace();
            }


        }

        /**每间隔0.1秒执行一次,快速补充测试数据用
         * */
        /*@Scheduled(fixedDelay = 100)*/
        /**每天下午3点最终确认，并向所有人发出报警信息
         * */
        @Scheduled(cron = "0 0 0 * * ?")
        public void S_C_A_T_D_T_Final_Confirmation () {
            try {
                ResultInfo resultInfo = start();
                resultInfo.setErrorMsg("点检业务系统即将崩溃，请将重要数据及时备份！并联系系统管理员！");
                sendResult(resultInfo,true);
            }catch (EncodeException| IOException exception) {
                exception.printStackTrace();
            }


        }
        /**点检业务数据库的系统自维护->处理器
         * */
        private ResultInfo start() throws EncodeException, IOException {
            ResultInfo resultInfo = new ResultInfo();
            int insert = 0;

            int orderByIDLimitPointGetDateCount;
            S_C_PointEntity orderByIDLimitPoint = s_c_pointMapper.findOrderByIDLimit1();



            if (orderByIDLimitPoint == null) {
                resultInfo.setFlag(false);
                resultInfo.setErrorMsg("无点位信息");
                return resultInfo;
            } else {
                if (orderByIDLimitPoint.getPointCount() == null) {
                    orderByIDLimitPointGetDateCount = 0;
                } else {
                    orderByIDLimitPointGetDateCount = orderByIDLimitPoint.getPointCount();
                }
            }

            List<S_C_PointEntity> s_c_pointEntities = s_c_pointMapper.selectList(null);

            for (S_C_PointEntity s_c_pointEntity : s_c_pointEntities) {
                QueryWrapper<S_C_Point_ContentEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("point_name", s_c_pointEntity.getPointName());
                QueryWrapper<S_C_DatesEntity> s_c_datesEntityQueryWrapper = new QueryWrapper<>();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String format = sdf.format(GetServerDate.tomorrow(new Date()));
                s_c_datesEntityQueryWrapper.eq("point", s_c_pointEntity.getPointName()).eq("date", format);
                List<S_C_Point_ContentEntity> s_c_point_contentEntities = s_c_point_contentMapper.selectList(queryWrapper);

                List<S_C_DatesEntity> s_c_datesEntities = s_c_datesMapper.selectList(s_c_datesEntityQueryWrapper);
                System.out.println(s_c_datesEntities);
                if (s_c_datesEntities.size() == 0) {
                    for (int i = 1; i <= orderByIDLimitPointGetDateCount; i++) {

                        if (s_c_pointEntity.getPointCount() == i) {

                            for (int j = 1; j <= s_c_point_contentEntities.size(); j++) {
                                S_C_DatesEntity s_c_datesEntity = new S_C_DatesEntity();
                                s_c_datesEntity.setPoint(s_c_pointEntity.getPointName());
                                s_c_datesEntity.setDate(GetServerDate.tomorrow(new Date()));
                                s_c_datesEntity.setPointContent(s_c_point_contentEntities.get(j - 1).getPointContent());
                                insert = s_c_datesMapper.insert(s_c_datesEntity);
                            }

                        }
                    }
                }
            }
            if (insert > 0) {
                resultInfo.setFlag(true);
                resultInfo.setErrorMsg("添加正常");

            } else {
                QueryWrapper<S_C_DatesEntity> s_c_datesEntityQueryWrapper = new QueryWrapper<>();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String format = sdf.format(new Date());

                s_c_datesEntityQueryWrapper.eq("date", format);
                List<S_C_DatesEntity> s_c_datesEntities = s_c_datesMapper.selectList(s_c_datesEntityQueryWrapper);
                if (s_c_datesEntities.size() > 0) {
                    resultInfo.setFlag(true);
                    resultInfo.setErrorMsg("验证成功！");
                }else {
                    resultInfo.setFlag(false);
                    resultInfo.setErrorMsg("日期表更新失败！");
                }
                /*resultInfo.setFlag(false);
                resultInfo.setErrorMsg("日期表更新失败！");*/
            }
            return resultInfo;
        }

    public ResultInfo todayStart() throws EncodeException, IOException {
        ResultInfo resultInfo = new ResultInfo();
        int insert = 0;

        int orderByIDLimitPointGetDateCount;
        S_C_PointEntity orderByIDLimitPoint = s_c_pointMapper.findOrderByIDLimit1();



        if (orderByIDLimitPoint == null) {
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("无点位信息");
            return resultInfo;
        } else {
            if (orderByIDLimitPoint.getPointCount() == null) {
                orderByIDLimitPointGetDateCount = 0;
            } else {
                orderByIDLimitPointGetDateCount = orderByIDLimitPoint.getPointCount();
            }
        }

        List<S_C_PointEntity> s_c_pointEntities = s_c_pointMapper.selectList(null);

        for (S_C_PointEntity s_c_pointEntity : s_c_pointEntities) {
            QueryWrapper<S_C_Point_ContentEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("point_name", s_c_pointEntity.getPointName());
            QueryWrapper<S_C_DatesEntity> s_c_datesEntityQueryWrapper = new QueryWrapper<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(new Date());
            s_c_datesEntityQueryWrapper.eq("point", s_c_pointEntity.getPointName()).eq("date", format);
            List<S_C_Point_ContentEntity> s_c_point_contentEntities = s_c_point_contentMapper.selectList(queryWrapper);

            List<S_C_DatesEntity> s_c_datesEntities = s_c_datesMapper.selectList(s_c_datesEntityQueryWrapper);
            System.out.println(s_c_datesEntities);
            if (s_c_datesEntities.size() == 0) {
                for (int i = 1; i <= orderByIDLimitPointGetDateCount; i++) {

                    if (s_c_pointEntity.getPointCount() == i) {

                        for (int j = 1; j <= s_c_point_contentEntities.size(); j++) {
                            S_C_DatesEntity s_c_datesEntity = new S_C_DatesEntity();


                            s_c_datesEntity.setPoint(s_c_pointEntity.getPointName());
                            s_c_datesEntity.setDate(new Date());
                            s_c_datesEntity.setPointContent(s_c_point_contentEntities.get(j - 1).getPointContent());
                            insert = s_c_datesMapper.insert(s_c_datesEntity);
                        }

                    }
                }
            }
        }
        if (insert > 0) {
            resultInfo.setFlag(true);
            resultInfo.setErrorMsg("添加正常");

        } else {
            QueryWrapper<S_C_DatesEntity> s_c_datesEntityQueryWrapper = new QueryWrapper<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(new Date());

            s_c_datesEntityQueryWrapper.eq("date", format);
            List<S_C_DatesEntity> s_c_datesEntities = s_c_datesMapper.selectList(s_c_datesEntityQueryWrapper);
            if (!s_c_datesEntities.isEmpty()) {
                resultInfo.setFlag(true);
                resultInfo.setErrorMsg("验证成功！");
            }else {
                resultInfo.setFlag(false);
                resultInfo.setErrorMsg("日期表更新失败！");
            }
                /*resultInfo.setFlag(false);
                resultInfo.setErrorMsg("日期表更新失败！");*/
        }
        return resultInfo;
    }


        private void sendResult(ResultInfo resultInfo,boolean flag) {
            try {
                MongoDB_S_C_WebSocketSendMessageEntity mongoDB_s_c_webSocketMessageEntity = new MongoDB_S_C_WebSocketSendMessageEntity();
                MongoDB_S_C_WebSocketMessageEntity messageEntity = new MongoDB_S_C_WebSocketMessageEntity();
                GetServerDate.getMessageTime(mongoDB_s_c_webSocketMessageEntity);
                GetServerDate.getMessageTime(messageEntity);

                if (!resultInfo.isFlag()) {
                    /*如果是严重消息则向所有人推送，所有人可查
                     */

                    List<URole_TBEntity> uRole_tbEntities = new ArrayList<>();
                    URole_TBEntity uRole_tbEntity = new URole_TBEntity();
                    if (flag) {
                        uRole_tbEntity.setUrole("r6");
                        uRole_tbEntities.add(uRole_tbEntity);
                        messageEntity.setURole_tbEntity(uRole_tbEntities);
                        messageEntity.setImportantNewsMessageEntityIs(true);
                        messageEntity.setImportantNewsMessage(new ImportantNewsMessageEntity().setImportantNewsMessage(resultInfo.getErrorMsg()));
                        /*转成消息推送的格式
                         */
                        mongoDB_s_c_webSocketMessageEntity.setMongoDB_s_c_webSocketMessageEntity(messageEntity);
                        messageCenterService.saveSysMessage(messageEntity);
                        WebSocketServer webSocketServer = new WebSocketServer();
                        webSocketServer.sendToUser(mongoDB_s_c_webSocketMessageEntity, MessageType.SysMessage);
                    }else {
                        /*如果不是严重消息则存储到系统管理员的信箱
                         */
                        uRole_tbEntity.setUrole("r5");
                        uRole_tbEntities.add(uRole_tbEntity);
                        messageEntity.setURole_tbEntity(uRole_tbEntities);
                        messageEntity.setImportantNewsMessageEntityIs(false);
                        messageEntity.setMessage(resultInfo.getErrorMsg());
                        /*转成消息推送的格式
                         */
                        mongoDB_s_c_webSocketMessageEntity.setMongoDB_s_c_webSocketMessageEntity(messageEntity);
                        /*存储到消息中心系统管理员可查*/
                        messageCenterService.saveSysMessage(messageEntity);

                        WebSocketServer webSocketServer = new WebSocketServer();
                        webSocketServer.sendToUser(mongoDB_s_c_webSocketMessageEntity,MessageType.SysMessage);
                    }
                }
            } catch (EncodeException | IOException encodeException) {
                encodeException.printStackTrace();
            }
        }

        public void tableDeduplication() {

            List<S_C_DatesEntity> s_c_datesEntities = s_c_datesMapper.selectList(null);
            for (S_C_DatesEntity s_c_datesEntity : s_c_datesEntities) {

            }
        }


}


